package org.nightrunner.d3.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.nightrunner.d3.dao.IGenericDao;
import org.nightrunner.d3.model.IPaginationInfo;
import org.nightrunner.d3.model.PaginationModel;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * parent genericDao of hibernate operation
 * 
 * @author NightRunner
 * 
 * @param <T>
 * @param <ID>
 */
@SuppressWarnings("unchecked")
public class GenericDao<T, ID extends Serializable> extends HibernateDaoSupport
		implements IGenericDao<T, ID> {

	private Log logger = LogFactory.getLog(getClass());

	protected Class<T> entityClass;

	public GenericDao() {
	}

	/**
	 * This method can automatically matching hibernate entity class
	 * 
	 * @return automatically match hibernate entity
	 */
	protected Class getEntityClass() {
		if (entityClass == null) {
			entityClass = (Class<T>) ((ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0];
			logger.debug("T class = " + entityClass.getName());
		}
		return entityClass;
	}

	public void saveOrUpdate(T t) throws DataAccessException {
		this.getHibernateTemplate().saveOrUpdate(t);
	}

	public T load(ID id) throws DataAccessException {
		T load = (T) getHibernateTemplate().load(getEntityClass(), id);
		return load;
	}

	public T get(ID id) throws DataAccessException {
		T load = (T) getHibernateTemplate().get(getEntityClass(), id);
		return load;
	}

	public boolean contains(T t) throws DataAccessException {
		return getHibernateTemplate().contains(t);
	}

	public void delete(T t, LockMode lockMode) throws DataAccessException {
		getHibernateTemplate().delete(t, lockMode);
	}

	public void delete(T t) throws DataAccessException {
		getHibernateTemplate().delete(t);
	}

	public void deleteAll(Collection<T> entities) throws DataAccessException {
		getHibernateTemplate().deleteAll(entities);
	}

	public List<T> find(String queryString, Object value)
			throws DataAccessException {
		List<T> find = (List<T>) getHibernateTemplate()
				.find(queryString, value);
		return find;
	}

	public List<T> find(String queryString, Object[] values)
			throws DataAccessException {
		List<T> find = (List<T>) getHibernateTemplate().find(queryString,
				values);
		return find;
	}

	public List<T> find(String queryString) throws DataAccessException {
		return (List<T>) getHibernateTemplate().find(queryString);
	}

	public void refresh(T t, LockMode lockMode) throws DataAccessException {
		getHibernateTemplate().refresh(t, lockMode);
	}

	public void refresh(T t) throws DataAccessException {
		getHibernateTemplate().refresh(t);
	}

	public Serializable save(T t) throws DataAccessException {
		return getHibernateTemplate().save(t);
	}

	public void saveOrUpdateAll(Collection<T> entities)
			throws DataAccessException {
		getHibernateTemplate().saveOrUpdateAll(entities);
	}

	public void update(T t, LockMode lockMode) throws DataAccessException {
		getHibernateTemplate().update(t, lockMode);
	}

	public void update(T t) throws DataAccessException {
		getHibernateTemplate().update(t);
	}

	public List<T> list() throws DataAccessException {
		return getHibernateTemplate().loadAll(getEntityClass());

	}

	public List<T> findByNamedQuery(String queryName)
			throws DataAccessException {
		return getHibernateTemplate().findByNamedQuery(queryName);
	}

	public List<T> findByNamedQuery(String queryName, Object value)
			throws DataAccessException {
		return getHibernateTemplate().findByNamedQuery(queryName, value);
	}

	public List<T> findByNamedQuery(String queryName, Object[] values)
			throws DataAccessException {
		return getHibernateTemplate().findByNamedQuery(queryName, values);
	}

	public List<T> findByIds(String[] ids) {

		SessionFactory sessionFactory = super.getSessionFactory();

		ClassMetadata meta = sessionFactory.getClassMetadata(getEntityClass()
				.getName());

		if (ids == null || ids.length == 0)
			return null;
		StringBuffer idString = new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			idString.append("'");
			idString.append(ids[i].trim());
			idString.append("'");
			if (i < ids.length - 1)
				idString.append(",");
		}
		idString.substring(0, idString.length() - 1);
		StringBuffer hql = new StringBuffer();
		String entity = getEntityClass().getName();
		hql.append("from ");
		hql.append(entity);
		hql.append(" where ");
		hql.append(meta.getIdentifierPropertyName());
		hql.append(" in (");
		hql.append(idString);
		hql.append(")");
		return this.find(hql.toString());
	}

	public List<T> findByIds(List<String> ids) {

		if (ids == null || ids.size() == 0)
			return null;
		return findByIds((String[]) ids.toArray());
	}

	public PaginationModel<List<T>> find(
			PaginationModel<List<T>> paginationModel) {
		Session session = this.getSession();
		String entityName = getEntityClass().getName();
		Query query = session.createQuery("from " + entityName + "");
		paginationModel.setHibernateQuery(query);
		return paginationModel;
	}

	public PaginationModel<List<T>> find(
			PaginationModel<List<T>> paginationModel, String where) {
		Session session = this.getSession();
		String entityName = getEntityClass().getName();
		Query query = session.createQuery("from " + entityName + " where "
				+ where);
		paginationModel.setHibernateQuery(query);
		return paginationModel;
	}

	public PaginationModel<List<T>> find(IPaginationInfo paginationInfo) {
		PaginationModel<List<T>> paginationModel = new PaginationModel<List<T>>();
		paginationModel.setPaginationInfo(paginationInfo);
		return find(paginationModel);
	}

	public PaginationModel<List<T>> find(IPaginationInfo paginationInfo,
			String where) {
		PaginationModel<List<T>> paginationModel = new PaginationModel<List<T>>();
		paginationModel.setPaginationInfo(paginationInfo);
		return find(paginationModel, where);
	}

	public void merge(T t) throws DataAccessException {
		getHibernateTemplate().merge(t);
	}
}
